# -*- coding: utf-8 -*-
import logging

from django.conf import settings
from django.views.decorators.http import require_GET

from api.lottery.handler import get_cyclical_latest_activity
from api.preset import handler
from api.preset.handler import get_reward_activity_types, get_available_lottery_preset, create_lottery_lites, \
    get_all_tab
from api.preset.model import PART_MODEL
from common.cache import redis_cache
from common.lottery import SSC_LOTTERY_TYPES, PK10_LOTTERY_TYPES, CP11X5_LOTTERY_TYPES, KS_LOTTERY_TYPES, \
    LF_LOTTERY_TYPES, TC_LOTTERY_TYPES, FC_LOTTERY_TYPES, FF_PK10_LOTTERY_TYPES, FF_KS_LOTTERY_TYPES, \
    FF_SSC_LOTTERY_TYPES, \
    FF11X5_LOTTERY_TYPES
from common.lottery.cyclical.bj_pk10.logic.activity import calc_term_by_ts as pk_calc_term_by_ts
from common.lottery.cyclical.bj_pk10.logic.order import RATE_CONFIG as PK_RATE_CONFIG
from common.lottery.cyclical.bj_pk10.model.order import get_avaliable_bet_type as pk10_get_available_type
from common.lottery.cyclical.bj_pk10.model.order import get_available_bet_type_v3 as pk10_get_available_type_v3
from common.lottery.cyclical.bj_pk10.model.order import get_available_bet_type_v4 as pk10_get_available_type_v4
from common.lottery.cyclical.cq_lf.logic.activity import calc_term_by_ts as lf_calc_term_by_ts
from common.lottery.cyclical.cq_ssc.logic.activity import calc_term_by_ts as ssc_calc_term_by_ts
from common.lottery.cyclical.fc3d.logic.activity import calc_term_by_ts as fc3d_calc_term_by_ts
from common.lottery.cyclical.ff_11x5.logic.activity import calc_term_by_ts as ff_sd_calc_term_by_ts
from common.lottery.cyclical.ff_ks.logic.activity import calc_term_by_ts as ff_ks_calc_term_by_ts
from common.lottery.cyclical.ff_ks.logic.order import RATE_CONFIG as FF_KS_RATE_CONFIG
from common.lottery.cyclical.ff_ks.model.order import get_available_bet_type_v3 as ff_ks_get_available_type_v3
from common.lottery.cyclical.ff_pk10.logic.activity import calc_term_by_ts as ff_pk_calc_term_by_ts
from common.lottery.cyclical.ff_pk10.logic.order import RATE_CONFIG as FF_PK_RATE_CONFIG
from common.lottery.cyclical.ff_pk10.model.order import get_avaliable_bet_type_v3 as ff_pk10_get_available_type_v3
from common.lottery.cyclical.ff_ssc.logic.activity import calc_term_by_ts as ff_ssc_calc_term_by_ts
from common.lottery.cyclical.js_ks.logic.activity import calc_term_by_ts as ks_calc_term_by_ts
from common.lottery.cyclical.js_ks.logic.order import RATE_CONFIG as KS_RATE_CONFIG
from common.lottery.cyclical.js_ks.model.order import get_available_bet_type as ks_get_available_type
from common.lottery.cyclical.js_ks.model.order import get_available_bet_type_v3 as ks_get_available_type_v3
from common.lottery.cyclical.js_ks.model.order import get_available_bet_type_v4 as ks_get_available_type_v4
from common.lottery.cyclical.lucky_farm.model import get_avaliable_bet_types as lf_get_available_type_v3
from common.lottery.cyclical.lucky_farm.order import RATE_CONFIG as LS_RATE_CONFIG
from common.lottery.cyclical.model import ACTIVITY_MODEL
from common.lottery.cyclical.pls.model import get_avaliable_bet_types as pls_get_available_type_v3
from common.lottery.cyclical.pls.order import RATE_CONFIG as FC3D_RATE_CONFIG
from common.lottery.cyclical.pls.order import RATE_CONFIG as PLS_RATE_CONFIG
from common.lottery.cyclical.sd_11x5.logic.activity import calc_term_by_ts as sd_calc_term_by_ts
from common.lottery.cyclical.sd_11x5.logic.order import RATE_CONFIG as SD_RATE_CONFIG
from common.lottery.cyclical.sd_11x5.model.order import get_available_bet_type_v3 as cp11x5_get_available_bet_types_v3
from common.lottery.cyclical.sd_11x5.model.order import get_available_bet_type_v4 as cp11x5_get_available_bet_types_v4
from common.lottery.cyclical.sd_11x5.model.order import get_avaliable_bet_type as cp11x5_get_available_bet_types
from common.lottery.cyclical.ssc.model import get_avaliable_bet_types as ssc_get_available_bet_types
from common.lottery.cyclical.ssc.model import get_avaliable_bet_types_v3 as ssc_get_available_bet_types_v3
from common.lottery.cyclical.ssc.order import RATE_CONFIG as SSC_RATE_CONFIG
from common.lottery.cyclical.tc_pls.logic.activity import calc_term_by_ts as pls_calc_term_by_ts
from common.preset.model.preset import PRESET_PARTS_TABLE
from common.transaction.model import WITHDRAW_TYPE
from common.utils import exceptions as err
from common.utils import tracker
from common.utils import tz
from common.utils.api import get_city
from common.utils.api import parse_p, check_params, get_client_ip
from common.utils.decorator import response_wrapper
from common.utils.exceptions import ParamError, ResourceNotFound, NoTerm, InvalidLottery
from common.utils.ua import shorten_ua
from common.withdraw import get_available_withdraw_type

_LOGGER = logging.getLogger(__name__)
_TRACKER = logging.getLogger('tracker')


def _get_reward_config(params):
    check_params(params, ['activity_type', 'bet_type', 'term'],
                 param_type_dct={
                     'activity_type': int, 'bet_type': int, 'term': str
                 })
    return handler.view_reward_config(params)


def _get_qqgroup_config(params):
    platform = params.get('platform', '')
    if platform.startswith('ios'):
        uin = redis_cache.get_ios_qq_group_uin()
        key = redis_cache.get_ios_qq_group_key()
        return {'uid': uin, 'key': key}
    elif platform == 'android':
        uin = redis_cache.get_ios_qq_group_uin()
        key = redis_cache.get_android_qq_group_key()
        return {'uid': uin, 'key': key}
    else:
        raise ParamError('parameter platform invalid')


@require_GET
@response_wrapper
def get_part(req, name):
    user_agent = shorten_ua(req.META.get('HTTP_USER_AGENT', ''))
    user_id = req.user_id
    ip = get_client_ip(req)
    query_dct = req.GET.dict()
    p = parse_p(query_dct.get('p'))
    tracker.track_active(user_id or 1, p.get('cvc'), p.get('aid'), p.get('chn'), ip, user_agent)
    if name not in PRESET_PARTS_TABLE:
        raise err.ParamError('part name %s not exist' % name)
    params = req.GET.dict()
    user_id = req.user_id
    p = parse_p(req.GET.get('p'))

    if name == 'reward':
        return _get_reward_config(params)
    if name == 'qqgroup':
        return _get_qqgroup_config(params)
    if name == 'float_icon' and p.get('cvc') < 7:
        raise ResourceNotFound('')

    data = handler.view_parts(name,
                              p.get('cvc'), p.get('chn'),
                              user_id, PART_MODEL.get(name))

    if name in ['loading', 'banner', 'shortcut']:
        for item in data:
            item['image'] = handler.get_fixed_bucket(item['image'])
    if name in ['discovery', 'float_icon']:
        for item in data:
            item['icon'] = handler.get_fixed_bucket(item['icon'])

    data = {
        'list': data
    }
    return data


@require_GET
@response_wrapper
def get_preset(req):
    """
    获取预置数据
    eg:
    {
        'last_modified': 2,
        'lottery': [],
        'float_icon': {}
    }
    """
    user_id = req.user_id
    query_dct = req.GET.dict()
    last_modified = int(query_dct.get('last_modified', 0))
    p = parse_p(query_dct.get('p'))
    tracker.track_active(user_id or 1, p.get('cvc'), p.get('aid'), p.get('chn'))
    data = handler.view_preset(
        p.get('cvc'), p.get('chn'), last_modified, user_id)
    data.update({
        'withdraw_types': get_available_withdraw_type()
    })
    if data.get('ipay'):
        data['ipay']['webmode'] = data['ipay'].get('webmode') or handler.is_senior_user(user_id)

    return data


_TAG = settings.QINIU_BUCKETS['default'] + 'o_1bg3cnj9tk5ufub1mf6otp9a4g.png'


@require_GET
@response_wrapper
def get_avaliable_lottery_v2(req):
    """
    获取可用的彩种，或单个彩种的可用玩法
    V2接口，玩法有分类，2级列表
    """
    lottery_type = req.GET.get('lottery_type')
    if lottery_type:  # 获取一个彩种的玩法
        lottery_type = int(lottery_type)
        if lottery_type in SSC_LOTTERY_TYPES:
            return {'list': ssc_get_available_bet_types()}
        elif lottery_type in CP11X5_LOTTERY_TYPES:
            return {'list': cp11x5_get_available_bet_types()}
        elif lottery_type in PK10_LOTTERY_TYPES:
            return {'list': pk10_get_available_type()}
        elif lottery_type in KS_LOTTERY_TYPES:
            return {'list': ks_get_available_type()}
        else:
            raise err.DataError('unsupport lottery type')
    else:  # 获取可用彩种
        reward_activity_types = get_reward_activity_types()
        p = req.GET.get('p')
        p_param = parse_p(p)
        lottery_list = get_available_lottery_preset(p_param)
        lottery_lites = create_lottery_lites(lottery_list)
        for each in lottery_lites:
            if each['play_id'] in reward_activity_types:
                each['tag'] = _TAG
        return lottery_lites


@require_GET
@response_wrapper
def get_available_lottery_v3(req):
    """
    获取可用的彩种，或单个彩种的可用玩法
    V2接口，玩法有分类，2级列表
    """
    lottery_type = req.GET.get('lottery_type')
    p = req.GET.get('p')
    p_param = parse_p(p)
    user_id = req.user_id
    cvc = p_param.get('cvc')
    if lottery_type:  # 获取一个彩种的玩法
        lottery_type = int(lottery_type)
        now = tz.now_ts()
        if lottery_type in SSC_LOTTERY_TYPES:
            _list = ssc_get_available_bet_types_v3()
            term = ssc_calc_term_by_ts(now)
            for li in _list:
                handler.fill_amount(lottery_type, li["list"], term, SSC_RATE_CONFIG)
        elif lottery_type in CP11X5_LOTTERY_TYPES:
            _list = cp11x5_get_available_bet_types_v3()
            term = sd_calc_term_by_ts(now)
            handler.fill_amount(lottery_type, _list, term, SD_RATE_CONFIG)

        elif lottery_type in PK10_LOTTERY_TYPES:
            _list = pk10_get_available_type_v3()
            term = pk_calc_term_by_ts(now)
            handler.fill_amount(lottery_type, _list, term, PK_RATE_CONFIG)

        elif lottery_type in KS_LOTTERY_TYPES:
            _list = ks_get_available_type_v3()
            term = ks_calc_term_by_ts(now)
            handler.fill_amount(lottery_type, _list, term, KS_RATE_CONFIG)

        elif lottery_type in LF_LOTTERY_TYPES:
            _list = lf_get_available_type_v3()
            term = lf_calc_term_by_ts(now)
            for li in _list:
                handler.fill_amount(lottery_type, li["list"], term, LS_RATE_CONFIG)

        elif lottery_type in TC_LOTTERY_TYPES:
            _list = pls_get_available_type_v3()
            term = pls_calc_term_by_ts(now)
            for li in _list:
                handler.fill_amount(lottery_type, li["list"], term, PLS_RATE_CONFIG)

        elif lottery_type in FC_LOTTERY_TYPES:
            _list = pls_get_available_type_v3()
            term = fc3d_calc_term_by_ts(now)
            for li in _list:
                handler.fill_amount(lottery_type, li["list"], term, FC3D_RATE_CONFIG)

        elif lottery_type in FF_KS_LOTTERY_TYPES:
            _list = ff_ks_get_available_type_v3()
            term = ff_ks_calc_term_by_ts(now)
            handler.fill_amount(lottery_type, _list, term, FF_KS_RATE_CONFIG)

        elif lottery_type in FF_PK10_LOTTERY_TYPES:
            _list = ff_pk10_get_available_type_v3()
            term = ff_pk_calc_term_by_ts(now)
            handler.fill_amount(lottery_type, _list, term, FF_PK_RATE_CONFIG)

        elif lottery_type in FF_SSC_LOTTERY_TYPES:
            _list = ssc_get_available_bet_types_v3()
            term = ff_ssc_calc_term_by_ts(now)
            for li in _list:
                handler.fill_amount(lottery_type, li["list"], term, SSC_RATE_CONFIG)

        elif lottery_type in FF11X5_LOTTERY_TYPES:
            _list = cp11x5_get_available_bet_types_v3()
            term = ff_sd_calc_term_by_ts(now)
            handler.fill_amount(lottery_type, _list, term, SD_RATE_CONFIG)

        else:
            raise err.DataError('unsupport lottery type')

        return {'list': _list}
    else:  # 获取可用彩种
        reward_activity_types = get_reward_activity_types()
        p = req.GET.get('p')
        p_param = parse_p(p)
        ip = get_client_ip(req)
        city = get_city(ip)
        chn = p_param.get('chn')
        lottery_list = get_available_lottery_preset(p_param, user_id)
        lottery_lites = create_lottery_lites(lottery_list)

        tab_list = get_all_tab()
        tabs_collection = []
        for tab in tab_list:
            if (tab.column_type == 3 and
                    chn in ('duiba4', 'duia2', 'duia3') and
                    city in (u'杭州', u'北京', u'杭州市', u'北京市')):
                continue
            if (chn in ('xiaomi',) and
                    city in (u'北京', u'上海', u'北京市', u'上海市')):
                continue
            tabs_collection.append({
                'tab_name': tab.name,
                'tab_id': tab.id,
                'column_type': tab.column_type,
                'group': []
            })

        for each in lottery_lites:
            if each['type'] in ACTIVITY_MODEL:
                try:
                    param = {'cvc': p_param.get('cvc'), 'chn': p_param.get('chn')}
                    each.update(get_cyclical_latest_activity(each['type'], param))
                except NoTerm:
                    each.update({'left_ts': -1})
                except InvalidLottery:
                    each.update({'left_ts': -2})

            if each['play_id'] in reward_activity_types:
                each['tag'] = _TAG
            tab_id = each.pop('tab')
            for tab in tabs_collection:
                if tab['tab_id'] == tab_id:
                    tab['group'].append(each)
        tabs_collection = filter(lambda tab: tab['group'], tabs_collection)

        return {'list': tabs_collection}


@require_GET
@response_wrapper
def get_available_lottery_v4(req):
    lottery_type = int(req.GET.get('lottery_type'))

    p = req.GET.get('p')
    p_param = parse_p(p)
    user_id = req.user_id
    cvc = p_param.get('cvc')

    now = tz.now_ts()
    if lottery_type in SSC_LOTTERY_TYPES:
        _list = ssc_get_available_bet_types_v3(cvc)
        term = ssc_calc_term_by_ts(now)
        for li in _list:
            handler.fill_amount(lottery_type, li["list"], term, SSC_RATE_CONFIG)
    elif lottery_type in CP11X5_LOTTERY_TYPES:
        _list = cp11x5_get_available_bet_types_v4()
        term = sd_calc_term_by_ts(now)
        for li in _list:
            handler.fill_amount(lottery_type, li["list"], term, SD_RATE_CONFIG)

    elif lottery_type in PK10_LOTTERY_TYPES:
        _list = pk10_get_available_type_v4(cvc)
        term = pk_calc_term_by_ts(now)
        for li in _list:
            handler.fill_amount(lottery_type, li["list"], term, PK_RATE_CONFIG)

    elif lottery_type in KS_LOTTERY_TYPES:
        _list = ks_get_available_type_v4(cvc)
        term = ks_calc_term_by_ts(now)
        for li in _list:
            handler.fill_amount(lottery_type, li["list"], term, KS_RATE_CONFIG)

    elif lottery_type in LF_LOTTERY_TYPES:
        _list = lf_get_available_type_v3()
        term = lf_calc_term_by_ts(now)
        for li in _list:
            handler.fill_amount(lottery_type, li["list"], term, LS_RATE_CONFIG)

    elif lottery_type in TC_LOTTERY_TYPES:
        _list = pls_get_available_type_v3()
        term = pls_calc_term_by_ts(now)
        for li in _list:
            handler.fill_amount(lottery_type, li["list"], term, PLS_RATE_CONFIG)

    elif lottery_type in FC_LOTTERY_TYPES:
        _list = pls_get_available_type_v3()
        term = fc3d_calc_term_by_ts(now)
        for li in _list:
            handler.fill_amount(lottery_type, li["list"], term, FC3D_RATE_CONFIG)

    elif lottery_type in FF_KS_LOTTERY_TYPES:
        _list = ks_get_available_type_v4(cvc)
        term = ff_ks_calc_term_by_ts(now)
        for li in _list:
            handler.fill_amount(lottery_type, li["list"], term, FF_KS_RATE_CONFIG)

    elif lottery_type in FF_PK10_LOTTERY_TYPES:
        _list = pk10_get_available_type_v4(cvc)
        term = ff_pk_calc_term_by_ts(now)
        for li in _list:
            handler.fill_amount(lottery_type, li["list"], term, FF_PK_RATE_CONFIG)

    elif lottery_type in FF_SSC_LOTTERY_TYPES:
        _list = ssc_get_available_bet_types_v3(cvc)
        term = ff_ssc_calc_term_by_ts(now)
        for li in _list:
            handler.fill_amount(lottery_type, li["list"], term, SSC_RATE_CONFIG)

    elif lottery_type in FF11X5_LOTTERY_TYPES:
        _list = cp11x5_get_available_bet_types_v4()
        term = ff_sd_calc_term_by_ts(now)
        for li in _list:
            handler.fill_amount(lottery_type, li["list"], term, SD_RATE_CONFIG)

    else:
        raise err.DataError('unsupport lottery type')

    return {'list': _list}
